<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>设置定时器</title>
<link href="https://cdn.bootcss.com/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.min.css" rel="stylesheet">
<script src="../scripts/jquery-3.4.0.min.js"></script>
<script src="../scripts/moment.js"></script>
<script src="https://cdn.bootcss.com/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>
</head>
<body>
  <?php require($_SERVER['DOCUMENT_ROOT'].'/common/header.html'); ?>
  <div class="container" style="width: 80%">
      <h1>设置定时器</h1>
      <br>
      <div class="row">
        <!-- 左侧 -->
        <div class="col-md-5"  id="mainid">
          <div class="panel panel-primary">
            <div class="panel-heading">
              <h3 class="panel-title">打开时间</h3>
            </div>
            <div class="panel-body">
              <label class="checkbox-inline">
                  <input type="checkbox" id="checkbox-open" checked="true">打开时间
              </label>
              <!--指定 date标记-->
              <div class='input-group date' id='datetimepicker1' style="width: 160px;">
                  <input type='text' id="startTime" class="form-control" style="font-size: 25px" value="08:00" />
                  <span class="input-group-addon">
                      <span class="glyphicon glyphicon-calendar"></span>
                  </span>
              </div>
            </div>
          </div>
          <div class="panel panel-primary">
            <div class="panel-heading">
              <h3 class="panel-title">关闭时间</h3>
            </div>
            <div class="panel-body">
              <label class="checkbox-inline">
                <input type="checkbox" id="checkbox-close" checked="true">关闭时间
              </label>
              <!--指定 date标记-->
              <div class='input-group date' id='datetimepicker2' style="width: 160px;">
                  <input type='text' id="stopTime" class="form-control" style="font-size: 25px" value="17:30"/>
                  <span class="input-group-addon">
                      <span class="glyphicon glyphicon-calendar"></span>
                  </span>
              </div>
            </div>
          </div>
          <div class="panel panel-primary">
            <div class="panel-heading">
              <h3 class="panel-title">重复</h3>
            </div>
            <div class="panel-body">
              <div>
                <label class="radio-inline" style="font-size: 20px">
                  <input type="radio" id="radio-1" name="repeat" checked="false">每天
                </label>
              </div>
              <div>
                <label class="radio-inline" style="font-size: 20px">
                  <input type="radio" id="radio-2" name="repeat">执行一次
                </label>
              </div>
              <div>
                <label class="radio-inline" style="font-size: 20px">
                  <input type="radio" id="radio-3" name="repeat">工作日
                </label>
              </div>
              <div>
                <label class="radio-inline" style="font-size: 20px">
                  <input type="radio" id="radio-4" name="repeat">自定义
                </label>
                <div style="margin-left: 30px;margin-top: 10px;" id="weekDiv" hidden="true">
                  <div>
                    <label class="checkbox-inline" style="font-size: 20px;">
                      <input type="checkbox" id="week-7" name="sunday">星期日
                    </label>
                    <label class="checkbox-inline" style="font-size: 20px;">
                      <input type="checkbox" id="week-1" name="monday" checked="true">星期一
                    </label>
                    <label class="checkbox-inline" style="font-size: 20px;">
                    <input type="checkbox" id="week-2" name="tuesday" checked="true">星期二
                    </label>
                    <label class="checkbox-inline" style="font-size: 20px;">
                      <input type="checkbox" id="week-3" name="wednesday" checked="true">星期三
                    </label>
                  </div>
                  <div>
                    <label class="checkbox-inline" style="font-size: 20px;">
                      <input type="checkbox" id="week-4" name="thursday" checked="true">星期四
                    </label>
                    <label class="checkbox-inline" style="font-size: 20px;">
                    <input type="checkbox" id="week-5" name="friday" checked="true">星期五
                    </label>
                    <label class="checkbox-inline" style="font-size: 20px;">
                    <input type="checkbox" id="week-6" name="saturday">星期六
                    </label>
                  </div>
                </div>
                
              </div>
            </div>
          </div>
          <div class="panel panel-primary">
            <div class="panel-heading">
              <h3 class="panel-title">执行</h3>
            </div>
            <div class="panel-body">
              <div style="float: right;">
                <button type="button" id="submit_btn" style="width: 80px;height: 40px;margin-right: 20px; font-size: 20px;" class="btn btn-success">确定</button>
                <a href="#" style="width: 80px;height: 40px;font-size: 20px;" class="btn btn-info" onClick="javascript :history.go(-1);">返回</a>
              </div>
              
            </div>
          </div>
        </div>

        <!-- 右侧 -->
        <div class="col-md-7">
          <div class="panel panel-primary">
            <div class="panel-heading">
              <h3 class="panel-title">消息区</h3>
            </div>
            <div class="panel-body">
              <pre id='msg' style="font-size: 20px"></pre>
            </div>
          </div>
        </div>
      </div>
  </div>
<script src="/scripts/mqttws31.js"></script>
<script>
  /**********************MQTT**************************************/
  var _deviceid = getUrlParam('deviceid');
  var _moduleid = getUrlParam('moduleid');
  var client;
  var connect_clientId = (new Date()).valueOf().toString();
  var pubTopic = 'device-'+_deviceid+"/setTime";
  $(function() {
    var host = '47.102.150.235';    
    var port = '61623';
    var clientId = connect_clientId;
    var user = 'admin';
    var password = 'password';
    client = new Messaging.Client(host, Number(port), clientId);
    client.onConnect = onConnect;
    client.onMessageArrived = onMessageArrived;
    client.onConnectionLost = onConnectionLost;            
    client.connect({
      userName:user, 
      password:password, 
      onSuccess:onConnect, 
      onFailure:onFailure
    }); 
    return false;
  });  

  // the client is notified when it is connected to the server.
  var onConnect = function(frame) {
    console.log("connected to MQTT");
    client.subscribe('device-'+_deviceid+"/feedback");
  };  
  function onFailure(failure) {
    console.log("failure");
    console.log(failure.errorMessage);
  }  

  function onMessageArrived(message) {
    var obj = JSON.parse(message.payloadString);
    console.log('收到订阅话题：device-'+_deviceid+"/feedback:",obj);
    //
    // for(let index in obj.data) 
    // {
    //   if(obj.data[index].value==0)
    //   {
    //     console.log('off:',"#state"+obj.data[index].moduleid);
    //     $("#state"+obj.data[index].moduleid).removeClass("led led_on led_off");
    //     $("#state"+obj.data[index].moduleid).addClass("led led_off");
    //     $("#state"+obj.data[index].moduleid).text("OFF");
    //   }
    //   else
    //   {
    //     console.log('on:',"#state"+obj.data[index].moduleid);
    //     $("#state"+obj.data[index].moduleid).removeClass("led led_on led_off");
    //     $("#state"+obj.data[index].moduleid).addClass("led led_on");
    //     $("#state"+obj.data[index].moduleid).text("ON");
    //   }
    // }
    
  }

  function onConnectionLost(responseObject) {
    if (responseObject.errorCode !== 0) {
      console.log(client.clientId + ": " + responseObject.errorCode + "\n");
    }
  }

  function publish(topic,text) {
    if (text) {
      message = new Messaging.Message(text);
      message.destinationName = topic;
      client.send(message);
    }
    return false;
  }
/******************************定时配置*************************************************/
  var user;
  // 显示正在加载动画
  var loading = layer.load(0);
  var switchTimer;
  // 配置时间选择器
  $(function () {
      $('#datetimepicker1').datetimepicker({
          format: 'HH:mm',
          locale: moment.locale('zh-cn')
      });
      $('#datetimepicker2').datetimepicker({
          format: 'HH:mm',
          locale: moment.locale('zh-cn')
      });
  });

  //获取用户登陆信息
  $.ajax({
    url: "/api/user/user.php",
    async: false, //同步
    success: function (res) {
      user = res;
      new Vue({
        el: '#header1',
        data: {
          user: user
        }
      })
      //关闭加载动画
      layer.close(loading); 
      updata();
    },
    error:function (res) {
        console.log('fail:',res);
    }
  });

  // 加载定时配置
  $.ajax({
    type:'POST',
    async: false, //异步
    url: "/api/device/get.module.php",
    data:{"userid":user.userid,"deviceid":_deviceid,'moduleid':_moduleid,'type':'switch'},
    success: function (res) {
      console.log('module：',res);
      switchTimer = JSON.parse(res.data[0].timer);
      if (switchTimer != null) {

        if (switchTimer.openTime=='null') 
          $("#checkbox-open").attr("checked", false);
        else
          $("#startTime").val(switchTimer.openTime);

        if (switchTimer.closeTime=='null')
          $("#checkbox-close").attr("checked", false);
        else
          $("#stopTime").val(switchTimer.closeTime);

        if (switchTimer.repeat=='everyDay')
          $("#radio-1").attr("checked", true);
        else
        if (switchTimer.repeat=='oneDay')
          $("#radio-2").attr("checked", true);
        if (switchTimer.repeat=='workingDay')
          $("#radio-3").attr("checked", true);  
        if (switchTimer.repeat=='userSet'){
          $("#radio-4").attr("checked", true);
          $("#weekDiv").show(); 
          console.log((1<<6));  
          if (switchTimer.week>>6&1) 
            $("#week-7").attr("checked", true);
          else
            $("#week-7").attr("checked", false);

          if (switchTimer.week>>5&1) 
            $("#week-6").attr("checked", true);
          else
            $("#week-6").attr("checked", false);

          if (switchTimer.week>>4&1) 
            $("#week-5").attr("checked", true);
          else
            $("#week-5").attr("checked", false);
          if (switchTimer.week>>3&1) 
            $("#week-4").attr("checked", true);
          else
            $("#week-4").attr("checked", false);
          if (switchTimer.week>>2&1) 
            $("#week-3").attr("checked", true);
          else
            $("#week-3").attr("checked", false);
          if (switchTimer.week>>1&1) 
            $("#week-2").attr("checked", true);
          else
            $("#week-2").attr("checked", false);
          if (switchTimer.week&1) 
            $("#week-1").attr("checked", true);
          else
            $("#week-1").attr("checked", false);
        }
        updata();
      }
    },
    error:function (res) {
      console.log('module：',res);
    }
  });

  var jsonStr;
  // 更新数据
  function updata(){
    var repeat;
    if ($("#radio-1").prop("checked")) {
      repeat = "everyDay";
    }
    else if ($("#radio-2").prop("checked")) {
      repeat = "oneDay";
    }
    else if ($("#radio-3").prop("checked")) {
      repeat = "workingDay";
    }
    else if ($("#radio-4").prop("checked")) {
      repeat = "userSet";
    }
    var obj;
    var obj={
      "moduleid": Number(_moduleid), 
      "repeat":repeat,
      "openTime": $("#checkbox-open").prop("checked")==true? $("#startTime").val():"null",      
      "closeTime": $("#checkbox-close").prop("checked")==true?$("#stopTime").val():"null",    
    }
    if (repeat=="userSet") {
      var temp = 0;

      temp |=($("#week-7").prop("checked")==true?1:0)<<6;
      temp |=($("#week-6").prop("checked")==true?1:0)<<5;
      temp |=($("#week-5").prop("checked")==true?1:0)<<4;
      temp |=($("#week-4").prop("checked")==true?1:0)<<3;
      temp |=($("#week-3").prop("checked")==true?1:0)<<2;
      temp |=($("#week-2").prop("checked")==true?1:0)<<1;
      temp |=($("#week-1").prop("checked")==true?1:0);
      $(obj).attr("week", temp);
    }
    var str = JSON.stringify(obj, null, 4) //使用四个空格缩进
    jsonStr = JSON.stringify(obj);
    $("#msg").text(str);
    return str;
  }
  // 监控点击事件
  $("body").on('click','#mainid',function(res){
    // 选择自定义时显示星期列表
    if($("#radio-4").prop("checked"))
      $("#weekDiv").show();
    else
      $("#weekDiv").hide();
    var str = updata();
  });
  $("body").on('blur','#mainid',function(res){
    var str = updata();
  });
  // 确定按钮
  $("body").on('click','#submit_btn',function(res){
    // 发布话题
    publish(pubTopic,jsonStr);
    //存储到数据库
    $.ajax({
      type:'POST',
      async: true, //异步
      url: "/api/device/device.switch.setTimer.php",
      data:{"userid":user.userid,"deviceid":_deviceid,'moduleid':_moduleid,'timer':jsonStr},
      success: function (res) {
        console.log('存储定时器成功：',res);
      },
      error:function (res) {
        console.log('存储定时器失败：',res);
      }
    });
    // 提示成功
    layer.alert('更新成功！', {
      skin: 'layui-layer-molv', //样式类名
      anim: 4, //动画类型
      time: 5000, //5s后自动关闭
      btn: ['好的']
      ,yes: function(){
        // 跳转回原来页面
        history.go(-1);
      }
    });
  });
</script>
<?php include $_SERVER ['DOCUMENT_ROOT']."/common/footer.php";?>
</body>
</html>